package cn.harmonyoslearn.navrouter.models;

import cn.harmonyoslearn.navrouter.datas.*;
import cn.harmonyoslearn.navrouter.utils.FileUtil;
import cn.harmonyoslearn.navrouter.utils.LogUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 单独处理router_map.json文件内容
 */
public class RouterMapModel {
    /**
     * 根目录路径
     */
    private final String basePath;
    private Map<String, RouterMap> routerMaps = new HashMap<>();

    public RouterMapModel(String basePath) {
        this.basePath = basePath;
        this.readObjectRouterMaps();
    }

    /**
     * 从项目中加载RouterMap；
     * 通过读取 build-profile.json5 中的 modules 来加载 RouterMap 数据
     */
    public void readObjectRouterMaps() {
        String buildProfileContent = FileUtil.readFileContent(this.basePath + "/build-profile.json5");
        LogUtil.i("RouterMapModel.readObjectRouterMaps", "buildProfileContent: " + buildProfileContent);
        ArrayList<String> routerMapPathList = new JsonValue(buildProfileContent).arrayList("modules", e -> {
            String path = e.getString("srcPath", "");
            String srcPath = this.basePath + path.replace(".", "");
            return srcPath + "/src/main/resources/base/profile/router_map.json";
        });

        for (String content : this.routerMaps.keySet()) {
            this.routerMaps.remove(content);
        }

        for (String path : routerMapPathList) {
            if (!FileUtil.isFile(path)) {
                continue;
            }

            String routerMapStr = FileUtil.readFileContent(path);
            this.routerMaps.put(path, new RouterMap(
                    new JsonValue(routerMapStr),
                    path
            ));
        }
    }

    /**
     * 添加文件到 router_map.json 中
     * @param filePath 文件夹路径，不能包括文件名称
     * @param pageName 创建的文件名称
     */
    public void addPage(String filePath, String pageName) {
        String routerMapPath = modelFilePath2RouterMapPath(filePath);
        LogUtil.i("RouterMapModel.addPage", "routerMapPath: " + routerMapPath + ", pageName: " + pageName);

        if (!FileUtil.isFile(routerMapPath)) {
            createRouterMapFile(routerMapPath);
        }

        String pageSourceFile = "src/" + filePath.split("/src/")[1];
        JsonValue routerInfo = new JsonValue(new HashMap<>());
        routerInfo.addString("name", pageName);
        routerInfo.addString("pageSourceFile", pageSourceFile);
        routerInfo.addString("buildFunction", "PageBuilder");

        RouterMap routerMap = routerMaps.get(routerMapPath);
        routerMap.routerMap.arrayList("routerMap").add(routerInfo);
    }

    /**
     * 删除文件
     * @param filePath 文件路径
     */
    public void deletePage(String routerMapPath, String filePath) {
        LogUtil.i("RouterMapModel.deletePage", "routerMapPath: " + routerMapPath + ", filePath: " + filePath);
        ArrayList<JsonValue> routerMap = new ArrayList<>();
        this.routerMaps.get(routerMapPath).routerMap.arrayList("routerMap", e -> {
            if (filePath.contains(e.getString("pageSourceFile", ""))) {
                return null;
            } else {
                return e;
            }
        }).forEach(e -> {
            if (e != null) {
                routerMap.add(e);
            }
        });

        this.routerMaps.get(routerMapPath).routerMap.value("routerMap").setValue(routerMap);
    }

    public void saveFile(String routerMapPath) {
        String routerMapStr = this.routerMaps.get(routerMapPath).routerMap.toJsonString();
        FileUtil.write(routerMapPath, routerMapStr, true);
    }

    public void saveFile() {
        this.routerMaps.forEach((key, value) -> {
            saveFile(key);
        });
    }

    /**
     * 获取所有RouterMap，拷贝的形式 <br>
     * key: router_map.json 的文件路径，绝对路径
     * @return 拷贝后的 RouterMap
     */
    public Map<String, RouterMap> getRouterMaps() {
        Map<String, RouterMap> routerMaps = new HashMap<>();
        for (String key : this.routerMaps.keySet()) {
            RouterMap routerMap = this.routerMaps.get(key);

            routerMaps.put(key, new RouterMap(
                    routerMap.routerMap.copy(),
                    routerMap.routerMapPath)
            );
        }
        return routerMaps;
    }

    /**
     * 更新RouterMap
     */
    public void setRouterMaps(Map<String, RouterMap> routerMaps) {
        this.routerMaps = routerMaps;
    }



    /**
     * 创建router_map.json文件
     *
     * @param routerMapPath router_map.json 的文件路径
     */
    private void createRouterMapFile(String routerMapPath) {
        String routerMapInitContent = """
                {
                  "routerMap": [
                  ]
                }""";
        FileUtil.write(routerMapPath, routerMapInitContent, true);
        FileUtil.refreshAndFindFileByPath(routerMapPath);

        // 将router_map添加到model.json5中去
        try {
            String modelJson5Path = modelFilePath2MainPath(routerMapPath) + "/module.json5";
            ServiceModel.updateFileContent(modelJson5Path, "module;routerMap", "$profile:router_map");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        // 加载RouterMap数据
        String content = FileUtil.readFileContent(routerMapPath);
        this.routerMaps.put(routerMapPath, new RouterMap(
                new JsonValue(content),
                routerMapPath
        ));
    }

    public static String modelFilePath2MainPath(String routerMapPath) {
        return routerMapPath.split("main/ets")[0].split("main/resources")[0] + "main";
    }

    public static String modelFilePath2RouterMapPath(String mainFilePath) {
        String content = modelFilePath2MainPath(mainFilePath);
        return content + "/resources/base/profile/router_map.json";
    }
}




























